﻿@using System.Text.Json
@using System.Text.Json.Nodes
@inject IHttpClientFactory HttpClientFactory

<MCard>
    <MToolbar
        Color="primary"
        Dark
        Flat>
        <MIcon Class="mr-2">mdi-silverware</MIcon>
        <MToolbarTitle>Local hotspots</MToolbarTitle>
    </MToolbar>

    <MRow>
        <MCol>
            <MCardText>
                <MTreeview
                    @bind-Value="_tree"
                    LoadChildren="Fetch"
                    TKey="string"
                    TItem="Item"
                    Items="items"
                    ItemKey="item => item.Id"
                    ItemText="item => item.Name"
                    ItemChildren="item => item.Children"
                    SelectedColor="indigo"
                    OpenOnClick
                    Selectable
                    ReturnObject
                    ExpandIcon="mdi-chevron-down"
                    OnIcon="mdi-bookmark"
                    OffIcon="mdi-bookmark-outline"
                    IndeterminateIcon="mdi-bookmark-minus">
                </MTreeview>
            </MCardText>
        </MCol>

        <MDivider Vertical></MDivider>

        <MCol
            Cols="12"
            Md="6">
            <MCardText>
                @if (_tree.Count == 0)
                {
                    <div
                        key="title"
                        class="text-h6 font-weight-light grey--text pa-4 text-center">
                        Select your favorite breweries
                    </div>
                }

                <ScrollXTransition>
                    @foreach (var (selection, i) in _tree.Select((item, i) => (item,i)))
                    {
                        <MChip
                            @key="i"
                            Color="grey"
                            Dark
                            Small
                            Class="ma-1">
                            <MIcon
                                Left
                                Small>
                                mdi-beer
                            </MIcon>
                            @selection
                        </MChip>
                    }
                </ScrollXTransition>
            </MCardText>
        </MCol>
    </MRow>

    <MDivider></MDivider>

    <MCardActions>
        <MButton
            Text
            OnClick="() => _tree.Clear()">
            Reset
        </MButton>

        <MSpacer></MSpacer>

        <MButton
            Class="white--text"
            Color="green darken-1"
            Depressed>
            Save
            <MIcon Right>
                mdi-content-save
            </MIcon>
        </MButton>
    </MCardActions>
</MCard>

@code {

    private HttpClient? _httpClient;
    private List<JsonNode> _breweries = new();
    private List<string> _tree = new();
    private List<string> _types = new();
    private List<Item> _items = new();
    private bool _itemsChanged = true;

    List<Item> items
    {
        get
        {
            if (!_itemsChanged)
            {
                return _items;
            }

            var top = new Item("1", "All Breweries", new List<Item>());

            if (_types.Any())
            {
                top.Children = _types.Select(type => new Item(type, getName(type), GetChildren(type))).ToList();
            }

            _items = new List<Item> {top};

            _itemsChanged = false;

            return _items;
        }
    }

    async Task Fetch(Item item)
    {
        _httpClient ??= HttpClientFactory.CreateClient("masa-docs");
        await Task.Delay(500);
        var response =  await _httpClient.GetAsync("_content/Masa.Blazor.Docs/data/demo/breweries.json");
        if (response.IsSuccessStatusCode)
        {
            var json = await response.Content.ReadAsStringAsync();
            _breweries = JsonSerializer.Deserialize<List<JsonNode>>(json) ?? new();

            foreach (var brewery in _breweries)
            {
                var type = (string)brewery["brewery_type"]!;
                if (!_types.Contains(type))
                {
                    _types.Add(type);
                }
            }

            _types.Sort();

            _itemsChanged = true;
        }
    }

    List<Item> GetChildren(string type)
    {
        List<Item> result = new();
        foreach (var brewery in _breweries)
        {
            if ((string?)brewery["brewery_type"] != type) continue;

            brewery["name"] = getName((string)brewery["name"]!);

            var item = new Item((string)brewery["id"]!, (string)brewery["name"]!, null);
            result.Add(item);
        }

        result.Sort((x, y) => string.Compare(x.Name, y.Name, StringComparison.Ordinal));

        return result;
    }

    string getName(string name)
    {
        return $"{name[0].ToString().ToUpper()}{name[1..]}";
    }

    public class Item
    {
        public string Id { get; set; }

        public string Name { get; set; }

        public List<Item>? Children { get; set; }
        
        public Item(string id, string name, List<Item>? children)
        {
            Id = id;
            Name = name;
            Children = children;
        }
    }

}